package com.huiminpay.test.rocketmq.message;

import com.huiminpay.test.rocketmq.modle.OrderExt;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @ClassName : ProducerSimpleTest
 * @Author : 阿泽
 * @Date: 2021/8/17 11:23
 * @Description :
 */
@Component
public class ProducerSimple {
    @Autowired
    RocketMQTemplate rocketMQTemplate;

    /**
     * 发送同步消息
     * @param topic 主题
     * @param msg
     */
    public void SendSyncMsg(String topic,String msg){
        //有返回值的 所以是同步方法
        SendResult sendResult = rocketMQTemplate.syncSend(topic, msg);
        System.out.println(sendResult);
    }

    /**
     * 异步方法
     * @param topic
     * @param msg
     */
    public void sendASyncMsg(String topic,String msg){
        rocketMQTemplate.asyncSend(topic, msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                //消息发送成功回调方法
                System.out.println(sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                //消息发送异常回调方法
                System.out.println(throwable.getMessage());
            }
        });
    }
    //发送同步方法自定义对象

    public void sendMsgByJson(String topic, OrderExt orderExt){

        rocketMQTemplate.convertAndSend(topic,orderExt);
        System.out.printf("send msg : %s",orderExt);
    }


    public void sendMsgByJsonDelay(String topic, OrderExt orderExt){

        //发送同步消息，消息内容将orderExt转为json
        Message<OrderExt> message = MessageBuilder.withPayload(orderExt).build();
        //指定发送超时时间（毫秒）和延迟等级
        this.rocketMQTemplate.syncSend(topic,message,1000,3);

        System.out.printf("send msg : %s",orderExt);
    }

}
